using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.CDS;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.FormsManagement;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.ScriptEngine;
using PHSRAG.Utility;
using System.Web.UI;
using PHSRAG.Security.Enumerations;
using ScriptReference = PHSRAG.Insight21.ScriptEngine.ScriptReference;



namespace PHSRAG.Insight21.COI
{
    /// <summary>
    /// COIOverview page displays the forms that make the COI.
    /// For a new COI, initially there would be only one form. Upon answering 
    /// this form, others forms may be displayed based on the answers provided
    /// to the initial form.
    /// 
    /// The links shown on this page are static links. 
    /// </summary>
    public partial class COIOverview : BasePage
    {
        #region Nested type: GridColumns

        private enum GridColumns
        {
            Id,
            QuestionnaireVersionId,
            RedirectToEntitySelection,
            Name,
            LastModified,
            StatusMeaning,
            Status,
            Action,
            FormComplete
        }

        #endregion

        #region Constants

        private const string ColumnCanBeRemoved = "CanBeRemoved";
        private const string ColumnDescription = "Description";
        private const string ColumnId = "Id";
        private const string ColumnLastModified = "LastModifiedDate";
        private const string ColumnName = "Name";
        private const string ColumnQAStatus = "Status";
        private const string ColumnQAStatusMeaning = "StatusMeaning";
        private const string ColumnQuestionnaireAnswerId = "QuestionnaireAnswerId";
        private const string ColumnQuestionnaireVersionId = "QuestionnaireVersionId";
        private const string ColumnRedirectToEntitySelection = "RedirectToEntitySelection";
        private const string ColumnRowHeader = "RowHeader";

        #endregion

        #region Instance Variable (private)

        private int _admPersonId;
        private bool _allFormsCompleted = true;
        private int _COITypeId;
        private ICachePolicy _applicationCachePolicy;
        private ICachePolicy _cachePolicy;
        private DataTable _charts;
        private ConflictOfInterest _coi;
        private int _coiId;
        private ICachePolicy _pageCachePolicy;

        //This flag is used to decide whether or not the headers should be displayed
        //If the page is to be displayed as a popup, then the header section is made invisible
        private bool _showAsPopUp;

        #endregion

        #region Page Event Handlers

        /// <summary>
        /// Looks for a cached person id and name. If found, displays the name in the breadcrumb.
        /// Displays the charts that are part of the COI being viewed 
        /// </summary>
        /// <param name="sender">Object that raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                if (Convert.ToBoolean(redirectToSubmissionPage.Value))
                {
                    Response.Redirect(Settings.GetKeyValue("SubNavigation.CoI.COISubmissionURL", string.Empty));
                }
                UserContext uc = (UserContext) _cachePolicy.GetCachedObject(UserContext.CacheKey);
                _admPersonId = uc.PersonId;
                string name = string.Format("{0}, {1}", uc.LastName, uc.FirstName);

                Hashtable incomingData = _pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                if (incomingData != null)
                {
                    if (incomingData.ContainsKey(Keys.FullNameKey))
                    {
                        name = Convert.ToString(incomingData[Keys.FullNameKey]);
                    }
                    if (incomingData.ContainsKey(Keys.AdmPersonIdKey))
                    {
                        _admPersonId = Convert.ToInt32(incomingData[Keys.AdmPersonIdKey]);
                    }
                    if (incomingData.ContainsKey(Keys.ShowAsPopUp))
                    {
                        _showAsPopUp = Convert.ToBoolean(incomingData[Keys.ShowAsPopUp]);
                    }

                    if (incomingData.ContainsKey(Keys.COIIdKey))
                    {
                        _coiId = Convert.ToInt32(incomingData[Keys.COIIdKey]);
                    }
                    else
                    {
                        throw new Exception("Page is being viewed out of context.");
                    }
                }
                else
                {
                    throw new Exception("Page is being viewed out of context.");
                }

                if (!Page.IsPostBack && postbackGuard.IsValid)
                {
                    //Load COI and cache
                    _coi = new ConflictOfInterest(_cachePolicy);
                    _coi.Load(DataAccess.GetConnectionString(), _coiId);
                    _coi.Cache();
                    //Setting the COIType 
                    _COITypeId = (int)_coi.COIType;
                    DisplayForms();
                    UpdateProgressBar();

                }
                else
                {
                    //Load COI from cache
                    _coi = (ConflictOfInterest) _cachePolicy.GetCachedObject(ConflictOfInterest.COIKey);
                    //Setting the COIType 
                    _COITypeId = (int)_coi.COIType;
                }
                //if page is being shown as popup, then hide the header section
                headerSection.Visible = !_showAsPopUp;

                breadCrumb.Add(((name.Length > 0) ? string.Format(_COITypeId == (int)Constants.COIType.AnnualCycle ? "Disclosure Summary for {0}" : "Real time Updates Disclosure Summary for {0}", name) : "Disclosure Summary"),
                Settings.GetKeyValue("SubNavigation.CoI.COIOverviewURL", ""),
                Settings.GetKeyValue("BreadCrumb.DetailPageLevel", 2));
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Fills the progressbar chunks with Green color for all the questionnaires that are complete.
        /// </summary>
        private void UpdateProgressBar()
        {
            if (_COITypeId == (int)Constants.COIType.AnnualCycle)
            {
                int inCompleteQuestionnaires = 0;
                ConflictOfInterest coi = new ConflictOfInterest(_cachePolicy);
                coi.Load(DataAccess.ConnectionString, _coiId);
                coi.LoadQuestionnaireAnswers();
                ArrayList qAs = coi.QuestionnaireAnswers;
                foreach (QuestionnaireAnswer qa in qAs)
                {

                    if (qa.Status != Constants.QuestionnaireAnswerStatus.Completed)
                    {
                        inCompleteQuestionnaires++;
                    }
                }

                if (inCompleteQuestionnaires > 0)
                {
                    ProgressText.Text = inCompleteQuestionnaires + (inCompleteQuestionnaires > 1 ? " forms" : " form") + " not yet completed";
                }
                else
                {
                    ProgressText.Text = "";
                }
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Page Initialization
        /// </summary>
        /// <param name="e">Arguments associated with the event</param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            _cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            _pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
            _applicationCachePolicy = (Policy.ICachePolicy) Application[Policy.Names.ApplicationCachePolicyKey];
        }


        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.header.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.breadCrumb.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnBreadCrumbNavigate);
            this.chartsGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.OnChartsGridItemCommand);
            this.chartsGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnChartsGridItemDataBound);
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }


        /// <summary>
        /// Adds a row with the specified details to the table which displays the forms
        /// </summary>
        /// <param name="table">Name of the table</param>
        /// <param name="position"></param>
        /// <param name="id">Questionnaire Answer id</param>
        /// <param name="name">Name of the Questionnaire/QuestionnaireAnswer</param>
        /// <param name="lastModified">Last Modified Date</param>
        /// <param name="qvId">QuestionnaireVersion Id</param>
        /// <param name="canBeRemoved">Indicates whether or not the form can be removed</param>
        /// <param name="rowHeader">Indicates whether or not the row should be highlighted</param>
        /// <param name="redirectToEntitySelection"></param>
        /// <param name="qaStatusMeaning"></param>
        /// <param name="qaStatus"></param>
        private void AddRow(DataTable table, int position, int id, string name, string lastModified,
            int qvId, bool canBeRemoved, bool rowHeader, bool redirectToEntitySelection,
            string qaStatusMeaning, string qaStatus)
        {
            DataRow dr = table.NewRow();
            dr[ColumnId] = id;
            dr[ColumnName] = name;
            dr[ColumnLastModified] = lastModified;
            dr[ColumnQuestionnaireVersionId] = qvId;
            dr[ColumnCanBeRemoved] = canBeRemoved;
            dr[ColumnRowHeader] = rowHeader;
            dr[ColumnRedirectToEntitySelection] = redirectToEntitySelection;
            dr[ColumnQAStatusMeaning] = qaStatusMeaning;
            dr[ColumnQAStatus] = qaStatus;
            table.Rows.InsertAt(dr, position);

            if (!rowHeader && qaStatus != FormsManagement.Constants.QuestionnaireAnswerStatus.Completed)
            {
                _allFormsCompleted = false;
                //hiddenAllFormsCompleted.Value = "false";
            }
        }


        /// <summary>
        /// Displays all the the forms that can be filled or are already filled by the user for the COI
        /// </summary>
        private void DisplayForms()
        {
            _charts = new DataTable();
            _charts.Columns.Add(ColumnId);
            _charts.Columns.Add(ColumnName);
            _charts.Columns.Add(ColumnLastModified);
            _charts.Columns.Add(ColumnQuestionnaireVersionId);
            _charts.Columns.Add(ColumnCanBeRemoved, typeof (Boolean));
            _charts.Columns.Add(ColumnRowHeader, typeof (Boolean));
            _charts.Columns.Add(ColumnRedirectToEntitySelection, typeof (Boolean));
            _charts.Columns.Add(ColumnQAStatusMeaning);
            _charts.Columns.Add(ColumnQAStatus);

//			showRemoveColumn = false;

            COIUser coiUser = new COIUser(_cachePolicy);
            coiUser.Load(DataAccess.ConnectionString, _admPersonId,0,0);
            bool isOutsideMember = coiUser.IsOutsideMember;

            //Gets a union of all the active Questionnaire Versions and questionnaire answers which were already saved.
            DataTable completeQAs = _coi.GetCompleteQuestionnaireAnswerList();

            string trusteeCondition = (isOutsideMember) ? " AND Name = 'Trustee Disclosure'" : " AND Name = 'Individual Disclosure'";

            //Get the answered Initial Questionnaire
            DataRow[] questionnaireAnswerRows = completeQAs.Select(
                "QuestionnaireCategory = '" + FormsManagement.Constants.COICategory.InitialQuestionnaire + "'" + trusteeCondition +
                    " AND QuestionnaireAnswerId <> 0");

            DataRow questionnaireAnswerRow;
            DataRow[] questionnaireRows;
            DataRow questionnaireRow;
            if (questionnaireAnswerRows.Length > 0)
            {
                questionnaireAnswerRow = questionnaireAnswerRows[0];
                AddRow(_charts, _charts.Rows.Count, Convert.ToInt32(questionnaireAnswerRow[ColumnQuestionnaireAnswerId]),
                    questionnaireAnswerRow[ColumnDescription].ToString(), questionnaireAnswerRow[ColumnLastModified].ToString(),
                    Convert.ToInt32(questionnaireAnswerRow[ColumnQuestionnaireVersionId]), false, false, false,
                    questionnaireAnswerRow[ColumnQAStatusMeaning].ToString(), questionnaireAnswerRow[ColumnQAStatus].ToString());
            }
            else //if initial questionnaire is not yet answered
            {
                questionnaireRows = completeQAs.Select(
                    "QuestionnaireCategory = '" + FormsManagement.Constants.COICategory.InitialQuestionnaire + "'" + trusteeCondition);

                if (questionnaireRows.Length > 0)
                {
                    questionnaireRow = questionnaireRows[0];
                    AddRow(_charts, _charts.Rows.Count, 0, questionnaireRow[ColumnDescription].ToString(),
                        "",
                        Convert.ToInt32(questionnaireRow[ColumnQuestionnaireVersionId]), false, false, false,
                        questionnaireRow[ColumnQAStatusMeaning].ToString(), questionnaireRow[ColumnQAStatus].ToString());
                }
            }

            RefCodes refCodes = (RefCodes) _applicationCachePolicy.GetCachedObject(RefCodes.CacheKey);


            if (!isOutsideMember && _coi.HasOutsideActivities == 'Y')
            {
                RefCode coiCategoryCode = refCodes.GetRefCode(FormsManagement.Constants.COICategory.Domain, FormsManagement.Constants.COICategory.OutsideActivity);

                //Outside Activities
                questionnaireAnswerRows = completeQAs.Select(
                    "QuestionnaireCategory = '" + FormsManagement.Constants.COICategory.OutsideActivity + "' AND AllowMultiple = 1 AND QuestionnaireAnswerId <> 0");
                if (questionnaireAnswerRows.Length > 0)
                {
                    //'Add your ...' link
                    questionnaireRows = completeQAs.Select(
                        "QuestionnaireCategory = '" + FormsManagement.Constants.COICategory.OutsideActivity + "' AND AllowMultiple = 1 AND QuestionnaireAnswerId = 0");
                    if (questionnaireRows.Length > 0)
                    {
                        questionnaireRow = questionnaireRows[0];
                        AddRow(_charts, _charts.Rows.Count, 0,
                            coiCategoryCode.Attributes[FormsManagement.Constants.COICategory.CategoryHeading].ToString(),
                            "",
                            Convert.ToInt32(questionnaireRow[ColumnQuestionnaireVersionId]), false, true, true,
                            questionnaireRow[ColumnQAStatusMeaning].ToString(), questionnaireRow[ColumnQAStatus].ToString());
                    }

//					showRemoveColumn = true;
                    foreach (DataRow dataRow in questionnaireAnswerRows)
                    {
                        AddRow(_charts, _charts.Rows.Count, Convert.ToInt32(dataRow[ColumnQuestionnaireAnswerId]),
                            dataRow[ColumnName].ToString(), dataRow[ColumnLastModified].ToString(),
                            Convert.ToInt32(dataRow[ColumnQuestionnaireVersionId]), true, false, false,
                            dataRow[ColumnQAStatusMeaning].ToString(), dataRow[ColumnQAStatus].ToString());
                    }
                }
            }

            if (_coi.HasEquityInterests == 'Y')
            {
                //Equity Interest
                questionnaireAnswerRows = completeQAs.Select(
                    "QuestionnaireCategory = '" + FormsManagement.Constants.COICategory.EquityInterest + "' AND AllowMultiple = 1 AND QuestionnaireAnswerId <> 0");
                if (questionnaireAnswerRows.Length > 0)
                {
                    RefCode coiCategoryCode = refCodes.GetRefCode(FormsManagement.Constants.COICategory.Domain, FormsManagement.Constants.COICategory.EquityInterest);

                    //Equity Interest Header
                    string header;
                    header = isOutsideMember ? coiCategoryCode.Attributes[FormsManagement.Constants.COICategory.CategoryHeadingForTrusteeAttribute].ToString() : coiCategoryCode.Attributes[FormsManagement.Constants.COICategory.CategoryHeadingForIndividualAttribute].ToString();

                    trusteeCondition = (isOutsideMember) ? " AND Name = 'Trustee Association'" : " AND Name = 'Your Equity Interests'";

                    //'Add your ...' link
                    questionnaireRows = completeQAs.Select(
                        "QuestionnaireCategory = '" + FormsManagement.Constants.COICategory.EquityInterest + "' AND AllowMultiple = 1 AND QuestionnaireAnswerId = 0" + trusteeCondition);
                    if (questionnaireRows.Length > 0)
                    {
                        questionnaireRow = questionnaireRows[0];
                        AddRow(_charts, _charts.Rows.Count, 0,
                            header,
                            "",
                            Convert.ToInt32(questionnaireRow[ColumnQuestionnaireVersionId]), false, true, true,
                            questionnaireRow[ColumnQAStatusMeaning].ToString(), questionnaireRow[ColumnQAStatus].ToString());
                    }

//					showRemoveColumn = true;
                    foreach (DataRow dataRow in questionnaireAnswerRows)
                    {
                        AddRow(_charts, _charts.Rows.Count, Convert.ToInt32(dataRow[ColumnQuestionnaireAnswerId]),
                            dataRow[ColumnName].ToString(), dataRow[ColumnLastModified].ToString(),
                            Convert.ToInt32(dataRow[ColumnQuestionnaireVersionId]), true, false, false,
                            dataRow[ColumnQAStatusMeaning].ToString(), dataRow[ColumnQAStatus].ToString());
                    }
                }
            }


            if (_coi.HasFamilyAssociations == 'Y')
            {
                RefCode coiCategoryCode = refCodes.GetRefCode(FormsManagement.Constants.COICategory.Domain, FormsManagement.Constants.COICategory.FamilyAssociation);

                trusteeCondition = (isOutsideMember) ? " AND Name = 'Trustee''s Family Associations and Equity Interests'" :
                                                                                                                               " AND Name = 'Your Family''s Associations and Equity Interests'";


                //Family Association
                questionnaireAnswerRows = completeQAs.Select(
                    "QuestionnaireCategory = '" + FormsManagement.Constants.COICategory.FamilyAssociation + "' AND AllowMultiple = 1 AND QuestionnaireAnswerId <> 0");
                if (questionnaireAnswerRows.Length > 0)
                {
                    //Family Association header && 'Add your ...' link
                    questionnaireRows = completeQAs.Select(
                        "QuestionnaireCategory = '" + FormsManagement.Constants.COICategory.FamilyAssociation + "' AND AllowMultiple = 1 AND QuestionnaireAnswerId = 0" + trusteeCondition);
                    if (questionnaireRows.Length > 0)
                    {
                        questionnaireRow = questionnaireRows[0];
                        AddRow(_charts, _charts.Rows.Count, 0,
                            coiCategoryCode.Attributes[FormsManagement.Constants.COICategory.CategoryHeading].ToString(),
                            "",
                            Convert.ToInt32(questionnaireRow[ColumnQuestionnaireVersionId]), false, true, true,
                            questionnaireRow[ColumnQAStatusMeaning].ToString(), questionnaireRow[ColumnQAStatus].ToString());
                    }

//					showRemoveColumn = true;
                    foreach (DataRow dataRow in questionnaireAnswerRows)
                    {
                        AddRow(_charts, _charts.Rows.Count, Convert.ToInt32(dataRow[ColumnQuestionnaireAnswerId]),
                            dataRow[ColumnName].ToString(), dataRow[ColumnLastModified].ToString(),
                            Convert.ToInt32(dataRow[ColumnQuestionnaireVersionId]), true, false, false,
                            dataRow[ColumnQAStatusMeaning].ToString(), dataRow[ColumnQAStatus].ToString());
                    }
                }
            }

            //Royalties
            if (!isOutsideMember && _coi.HasRoyalties == 'Y')
            {
                RefCode coiCategoryCode = refCodes.GetRefCode(FormsManagement.Constants.COICategory.Domain, FormsManagement.Constants.COICategory.Royalty);

                //Royalty
                questionnaireAnswerRows = completeQAs.Select(
                    "QuestionnaireCategory = '" + FormsManagement.Constants.COICategory.Royalty + "' AND AllowMultiple = 1 AND QuestionnaireAnswerId <> 0");
                if (questionnaireAnswerRows.Length > 0)
                {
                    //Royalty header && 'Add your ...' link
                    questionnaireRows = completeQAs.Select(
                        "QuestionnaireCategory = '" + FormsManagement.Constants.COICategory.Royalty + "' AND AllowMultiple = 1 AND QuestionnaireAnswerId = 0");
                    if (questionnaireRows.Length > 0)
                    {
                        questionnaireRow = questionnaireRows[0];
                        AddRow(_charts, _charts.Rows.Count, 0,
                            coiCategoryCode.Attributes[FormsManagement.Constants.COICategory.CategoryHeading].ToString(),
                            "",
                            Convert.ToInt32(questionnaireRow[ColumnQuestionnaireVersionId]), false, true, true,
                            questionnaireRow[ColumnQAStatusMeaning].ToString(), questionnaireRow[ColumnQAStatus].ToString());
                    }

//					showRemoveColumn = true;
                    foreach (DataRow dataRow in questionnaireAnswerRows)
                    {
                        AddRow(_charts, _charts.Rows.Count, Convert.ToInt32(dataRow[ColumnQuestionnaireAnswerId]),
                            dataRow[ColumnName].ToString(), dataRow[ColumnLastModified].ToString(),
                            Convert.ToInt32(dataRow[ColumnQuestionnaireVersionId]), true, false, false,
                            dataRow[ColumnQAStatusMeaning].ToString(), dataRow[ColumnQAStatus].ToString());
                    }
                }
            }
            BindGrid();
        }


        /// <summary>
        /// Binds the table to the grid
        /// </summary>
        private void BindGrid()
        {
            chartsGrid.DataSource = _charts;
            chartsGrid.DataBind();
            if (_COITypeId == (int)Constants.COIType.RealTimeUpdate)
            {
                chartsGrid.Columns[(int)GridColumns.FormComplete].Visible = false;
               // chartsGrid.Columns[(int)GridColumns.Action].HeaderStyle.Width = 125;
            }
            ////if (_coi.Status != COI.Constants.COIStatus.Submitted)
            ////	chartsGrid.Columns[(int)GridColumns.Remove].Visible = showRemoveColumn;
            if (_allFormsCompleted && !Page.ClientScript.IsStartupScriptRegistered("SubmissionAlert") && (_COITypeId ==(int)Constants.COIType.AnnualCycle))
            {
                //TODO:
                Page.ClientScript.RegisterStartupScript(GetType(), "SubmissionAlert",
                    "<script type=\"text/javascript\">ShowSubmissionAlert();</script>");
            }

            //To Audit the RTU COI on completion of all Questionnaires.
            if (_allFormsCompleted && _COITypeId == (int)Constants.COIType.RealTimeUpdate && Request.UrlReferrer.ToString().Contains("COIAnswerQuestionnairePage"))
            {
                _coi.AuditCOIChanges(Constants.COIActionsForAudit.CompletedQuestionnaires);
            }
        }


        /// <summary>
        /// Remove the fwkdomainuserid and the username, if exists, from the cache
        /// </summary>
        private void UncacheUserDetails()
        {
            Hashtable incomingData = _pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
            if (incomingData != null)
            {
                if (incomingData.ContainsKey(Keys.FullNameKey))
                {
                    incomingData.Remove(Keys.FullNameKey);
                }
                if (incomingData.ContainsKey(Keys.AdmPersonIdKey))
                {
                    incomingData.Remove(Keys.AdmPersonIdKey);
                }
            }
        }


        /// <summary>
        /// Removes COI and COI Id from cache
        /// </summary>
        private void UncacheCOIDetails()
        {
            Hashtable incomingData = _pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
            if (incomingData != null)
            {
                if (incomingData.ContainsKey(Keys.COIIdKey))
                {
                    incomingData.Remove(Keys.COIIdKey);
                }
            }
            if (_coi != null)
            {
                _coi.UnCache();
            }
        }

        /// <summary>
        /// Updates the corresponding disclosure form
        /// </summary>
        private void UpdateDisclosure(QuestionnaireAnswer questAnswer)
        {
            Script answerFillerScript =
                (Script) questAnswer.QuestionnaireVersion.Scripts[FormsManagement.Constants.ScriptType.AnswerFiller];

            if (answerFillerScript != null)
            {
                using (ScriptEngineHost scriptHost =
                    new ScriptEngineHost(
                        string.Format("{0}{1}", questAnswer.QuestionnaireVersionId,
                            ScriptEngine.Constants.RootMoniker.AnswerFillerScriptMoniker),
                        ScriptEngine.Constants.RootNamespaces.AnswerFillerScript,
                        true))
                {
                    ArrayList refs = ScriptReference.GetAllScriptReferences(
                        DataAccess.GetConnectionString());

                    for (int i = 0; i < refs.Count; ++i)
                    {
                        ScriptReference reference = (ScriptReference) refs[i];
                        scriptHost.AddDLLReference(reference.Path);
                    }


                    // add the connection string
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.ConnectionString,
                        DataAccess.GetConnectionString());
                    // add the caching policy
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.CachePolicy, _cachePolicy);
                    // add this COI as an intrinsic.
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.COI, _coi);
                    // add the QuestionnaireAnswer
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.QuestionnaireAnswer,
                        questAnswer);
                    // add the params
                    COIParams coiParams = new COIParams();
                    coiParams.OutsideEntityName = questAnswer.Name;
                    coiParams.OutsideEntitySelectedValue = questAnswer.ExternalId;
                    coiParams.MarkForDeletion = true;
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.COIParams,
                        coiParams);


                    // compile and run the script.
                    if (scriptHost.Compile(answerFillerScript))
                    {
                        scriptHost.RunScript(answerFillerScript,
                            ScriptEngine.Constants.AssemblyType.AnswerFillerScript,
                            ScriptEngine.Constants.MethodsToRun.Main);
                    }
                }
            }
        }

        #endregion

        #region Control Events

        /// <summary>
        /// Event generated when the user clicks on any of the links in the grid.
        /// 
        /// If the user clicks on Remove, then the corresponding questionnaire answer is removed and the grid is bound again.
        /// Redirects the user to Entity selected page, if any of the 'Add your ...' links are clicked.
        /// else redirects the user to the Answer Questionnaire page
        /// </summary>
        /// <param name="source">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnChartsGridItemCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "SelectForm")
                {
                    Hashtable outgoingData = _pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                    DataGridItem gridItem = chartsGrid.Items[e.Item.ItemIndex];
                    outgoingData[Keys.QuestionnaireVersionIdKey] = Convert.ToInt32(gridItem.Cells[(int) GridColumns.QuestionnaireVersionId].Text);
                    outgoingData[Keys.QuesionnaireAnswerIdKey] = Convert.ToInt32(gridItem.Cells[(int) GridColumns.Id].Text);
                    _pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

                    if (bool.Parse(gridItem.Cells[(int) GridColumns.RedirectToEntitySelection].Text))
                    {
                        Response.Redirect(Settings.GetKeyValue("SubNavigation.CoI.EntitySelectionPageURL", ""), false);
                    }
                    else
                    {
                        Response.Redirect(Settings.GetKeyValue("SubNavigation.CoI.AnswerChartURL", ""), false);
                    }
                }
                else if (e.CommandName == "RemoveForm")
                {
                    int qAId = Convert.ToInt32(chartsGrid.Items[e.Item.ItemIndex].Cells[(int) GridColumns.Id].Text);

                    QuestionnaireAnswer removedQuestionnaireAnswer = new QuestionnaireAnswer(_cachePolicy);
                    removedQuestionnaireAnswer.Load(DataAccess.ConnectionString, qAId);
                    //Call the answer filler script to update the disclosure form
                    UpdateDisclosure(removedQuestionnaireAnswer);
                    _coi.RemoveQuestionnaireAnswer(qAId);

                    DisplayForms();
                    UpdateProgressBar();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }


        /// <summary>
        /// Checks if a row is to be displayed as a header and highlights it appropriately.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnChartsGridItemDataBound(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    DataRowView dataRowView = (DataRowView) e.Item.DataItem;
                    if (Convert.ToBoolean(dataRowView.Row["RowHeader"]))
                    {
                        e.Item.BackColor = Color.Orange;
                        e.Item.FindControl("addNew").Visible = true;
                    }
                    else if (_coi.Status == Constants.COIStatus.Submitted)
                    {
                        e.Item.FindControl("addNew").Visible = true;
                    }

                    if (_coi.Status != Constants.COIStatus.Submitted && !Convert.ToBoolean(dataRowView["RowHeader"]))
                    {
                        (e.Item.FindControl("updateForm")).Visible = true;

                        if (Convert.ToBoolean(dataRowView.Row["CanBeRemoved"]))
                        {
                            ImageButton removeForm = (ImageButton) e.Item.FindControl("removeForm");
                            removeForm.Attributes.Add("onclick", "javascript:return confirm('Do you really want to remove?');");
                            removeForm.Visible = true;
                        }
                    }

                    if (!Convert.ToBoolean(dataRowView["RowHeader"]))
                    {
                        System.Web.UI.WebControls.Label FormStatusIndicatior = e.Item.FindControl("FormStatusIndicatior") as System.Web.UI.WebControls.Label;

                        if (((Label)e.Item.FindControl("lblQAStatus")).Text == FormsManagement.Constants.QuestionnaireAnswerStatus.Completed)
                        {
                            FormStatusIndicatior.Text = "YES";
                        }
                        else if (((Label)e.Item.FindControl("lblQAStatus")).Text != FormsManagement.Constants.QuestionnaireAnswerStatus.Completed)
                        {
                            FormStatusIndicatior.Text = "NO";
                            FormStatusIndicatior.ForeColor = System.Drawing.Color.Red;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }


        /// <summary>
        /// Resets the subnavigation and submodnavigation selected links before the header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                coiSubNavigation.Reset();
                coiSubModNavigation.Reset();
                UncacheUserDetails();
                UncacheCOIDetails();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }


        /// <summary>
        /// Resets the submodnavigation selected link before the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnBreadCrumbNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                coiSubModNavigation.Reset();
                UncacheUserDetails();
                UncacheCOIDetails();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion
    }
}